package com.freesky.biz.psbc.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freesky.biz.utils.AbChinaUtils;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.biz.utils.WxPayUtils;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 邮储券对接接口
 */
@Service
@Slf4j
public class PsbcCommService {

    @Value("${psbc.configs.apiKey}")
    private String API_KEY;

    @Value("${psbc.configs.privateKey}")
    private String RSA_PRIVATE_KEY;

    @Value("${psbc.configs.publicKey}")
    private String RSA_PUBLIC_KEY;

    @Value("${psbc.configs.bankPublicKey}")
    private String RSA_BANK_PUBLIC_KEY;

    @Value("${psbc.configs.tokenPrivateKey}")
    private String TOKEN_RSA_PRIVATE_KEY;

    private String PREFIX_URL = "https://wap.fujian.psbc.com/wxfwh_api";

    public AjaxResult commService(String orderNo,
                                  String cpnCode,
                                  String codeUse){

//        String API_KEY = "de60bbb7f4f645649662c2835b8fced4";
//        String RSA_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUMJUaNpJUxO8SLIzHcGgI8jXzDHjB2dtZ8/vX/QrYEFibvTdSB7XGw+KRW1dO1k6eSBMAE+ci0IbNKAvDVv7l6uMp+FUH9PSjCFCH+wGfgJxrL+R6oSVyn2RrieH4AcZWyU3hLVTNQ4hr2zuMG4lVLV/Wvu9LS7x84a8F1M6ngQIDAQAB";
//        String RSA_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJQwlRo2klTE7xIsjMdwaAjyNfMMeMHZ21nz+9f9CtgQWJu9N1IHtcbD4pFbV07WTp5IEwAT5yLQhs0oC8NW/uXq4yn4VQf09KMIUIf7AZ+AnGsv5HqhJXKfZGuJ4fgBxlbJTeEtVM1DiGvbO4wbiVUtX9a+70tLvHzhrwXUzqeBAgMBAAECgYEAgYvnDL9gNRLkHHMtrrwpdoineQ4SEwUsqPqN00e2zyObEqrbTa7Hzjc4PfIn5RecKuq/EXZUvS6maXr0rZPDyEr+f5PU0l97Y99vO0prVqbU9rMrDb7Lf8vnshLNUNDOlXhSiAG7RaQR15fqOF1JbGJVY6YD2dpJK6f/9QW65EECQQDgyi9UM1n/36+A10cT/swV5cUFbqjb97tlVVwlbtpEyxmJGjBID7zcdYRjihPSmMcd2+NibDDIygawMv+MA5+9AkEAqMPD65+Ip4DtVRe5btGiM6pPQ9m1oRrGucQk4gM/omyeHIJCwkJVDp72FIGDsLjjzNcEYSTAMBvGtR+YzXMRFQJAefdZ/L6sG3hb+nVUHJZIV61G3G6xckCVTiMljy35ghAM9+Xcwoy/dYLR5Uxa+w5oI1xWoOWBBsEPJfVV0Lt6pQJAbSQFfUjz6FfBpKkuG9Po0P7QOjH+e0zEvfhyXdP6AEG8UvWO1PBu74Cv5f0IPG6lq6BWTbilrbcY36OqfxtuLQJAfBnTjqEBw8VuHYnyvN9+RoROKQ/pSaHfeMe1iUCAW2kkld6YKkGBI6D59/05oG5Av6Qp132AFsWZm/64laP2VA==";

        try {
            Map<String, String> dataParam = new HashMap<>();
            dataParam.put("app_id", "TP9011"); //TP9011，TP9026
            dataParam.put("api_code", "2001");
            dataParam.put("req_no", SeqUtil.getSeqId());
            dataParam.put("order_no", Base64.encodeBase64String(AbChinaUtils.encryptPublicKey(orderNo.getBytes(), RSA_PUBLIC_KEY)));
            dataParam.put("cpn_code", Base64.encodeBase64String(AbChinaUtils.encryptPublicKey(cpnCode.getBytes(), RSA_PUBLIC_KEY)));

            dataParam.put("code_use", codeUse);
            dataParam.put("create_time_stamp", DateUtil.format(new Date(),"yyyyMMddHHmmss"));
            dataParam.put("time_stamp", String.valueOf(System.currentTimeMillis()));
            dataParam.put("nonce_str", WxPayUtils.generateNonceStr());

            String oriSignInfo = AbChinaUtils.sortMap(dataParam) + "&key=" + API_KEY;
            String md5Hex = DigestUtils.md5Hex(oriSignInfo).toUpperCase();
            String signInfo = Base64.encodeBase64String(AbChinaUtils.encryptPublicKey(md5Hex.getBytes(), RSA_PUBLIC_KEY));
            dataParam.put("sign", signInfo);
            log.info("oriSignInfo：" + oriSignInfo + ",md5:" + md5Hex +",signInfo:"+signInfo);
            log.info(JSON.toJSONString(dataParam));

            //https://wap.fujian.psbc.com/
            //https://wechat.herunxx.cn/wxfwh_api/interface/commService
            String respInfo = HttpRequest.post(PREFIX_URL + "/interface/commService")
                    .header(Header.USER_AGENT, "Chrome")
                    .header(Header.CONTENT_TYPE, "application/json;charset=UTF-8")
                    .charset("utf8")
                    .body(JSON.toJSONString(dataParam))
                    .timeout(5000)
                    .execute().body();
            log.info("Resp:" + respInfo);

            JSONObject resultJsonObject = JSONObject.parseObject(respInfo);
            if("0000".equalsIgnoreCase(resultJsonObject.getString("code"))){
                return AjaxResult.success(resultJsonObject.getString("message"));
            } else {
                return AjaxResult.error(resultJsonObject.getString("message"));
            }
        } catch (Exception ioe){
            log.info(ioe.getMessage());
            return AjaxResult.error("操作失败，系统异常!");
        }
    }

    public AjaxResult weixinStock(String bankNo,String mchId,
                                  String stockId,
                                  String couponId,
                                  String status,
                                  String merchNo,
                                  String consumeTime,
                                  String storeNo) throws Exception{

        Map<String, String> dataParam = new HashMap<>();
        dataParam.put("app_id","TP9011");       //TP9026
        dataParam.put("api_code","2003");
        dataParam.put("time_stamp",String.valueOf(System.currentTimeMillis()));
        dataParam.put("nonce_str", WxPayUtils.generateNonceStr());
        dataParam.put("req_no", bankNo);

        dataParam.put("stock_creator_mchid", mchId);
        dataParam.put("stock_id", stockId);
        dataParam.put("coupon_id", Base64.encodeBase64String(AbChinaUtils.encryptPublicKey(couponId.getBytes(),RSA_PUBLIC_KEY)));

        dataParam.put("status", status);
        dataParam.put("merch_no", merchNo);
        dataParam.put("store_no", storeNo);
        //DateUtil.format(new Date(),"yyyyMMddHHmmss")
        dataParam.put("create_time_stamp",consumeTime);

        String oriSignInfo = AbChinaUtils.sortMap(dataParam)+"&key="+API_KEY;
        String md5Hex = DigestUtils.md5Hex(oriSignInfo).toUpperCase();
        String signInfo = Base64.encodeBase64String(AbChinaUtils.encryptPublicKey(md5Hex.getBytes(), RSA_PUBLIC_KEY));
        dataParam.put("sign", signInfo);

        log.info("oriSignInfo："+oriSignInfo+",md5:"+md5Hex);
        log.info("sign:"+signInfo);
        log.info(JSON.toJSONString(dataParam));

        String respInfo = HttpRequest.post(PREFIX_URL + "/interface/commService")
                .header(Header.USER_AGENT, "Chrome")
                .header(Header.CONTENT_TYPE,"application/json;charset=UTF-8")
                .charset("utf8")
                .body(JSON.toJSONString(dataParam))
                .timeout(5000)
                .execute().body();
        log.info("Resp:"+respInfo);
        JSONObject resultJsonObject = JSONObject.parseObject(respInfo);
        if("0000".equalsIgnoreCase(resultJsonObject.getString("code"))){
            return AjaxResult.success(resultJsonObject.getString("message"));
        } else {
            return AjaxResult.error(resultJsonObject.getString("message"));
        }
    }

}
